//
//  NSMutableAttributedString+Page.m
//  富文本Demo
//
//  Created by Zeasn on 2018/2/24.
//  Copyright © 2018年 dreamer. All rights reserved.
//

#import "NSMutableAttributedString+Page.h"

#import <CoreText/CTFramesetter.h>

@implementation NSMutableAttributedString (Page)

- (NSArray *)pageRangeArrayWithConstrainedToSize:(CGSize)size {
    NSMutableAttributedString *mutableAttributedString = self;
    NSMutableArray * resultRange = [NSMutableArray array];
    
    CGRect rect = [mutableAttributedString boundingRectWithSize:size options:NSStringDrawingUsesFontLeading|NSStringDrawingUsesLineFragmentOrigin context:nil];
    
    NSInteger rangeIndex = 0;
    do {
        NSUInteger length = MIN(600, mutableAttributedString.length - rangeIndex);
        NSAttributedString * childString = [mutableAttributedString attributedSubstringFromRange:NSMakeRange(rangeIndex, length)];
        CTFramesetterRef childFramesetter = CTFramesetterCreateWithAttributedString((__bridge CFAttributedStringRef) childString);
        UIBezierPath * bezierPath = [UIBezierPath bezierPathWithRect:rect];
        CTFrameRef frame = CTFramesetterCreateFrame(childFramesetter, CFRangeMake(0, 0), bezierPath.CGPath, NULL);
        
        CFRange range = CTFrameGetVisibleStringRange(frame);
        NSRange r = {rangeIndex, range.length};
        if (r.length > 0) {
            [resultRange addObject:[NSValue valueWithRange:r]];
        }
        rangeIndex += r.length;
        
        CFRelease(frame);
        CFRelease(childFramesetter);
    } while (rangeIndex < mutableAttributedString.length && mutableAttributedString.length > 0);
    
    return resultRange;
}

@end
